package com.adolph.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * 〈功能概述〉<br>
 *  Buffer的分散和聚合
 *  Scattering:数据写入到Buffer时，可以采用Buffer数组，一次写入
 *  Gathering:从Buffer中读数据时，可以采用Buffer数组，一次读
 * @author: wangxiangjun
 * @date: 2020-10-01 10:12
 */

public class NIOScatteringAndGathering {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(8888);
        //绑定端口并启动
        serverSocketChannel.socket().bind(inetSocketAddress);
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(2);
        byteBuffers[1] = ByteBuffer.allocate(5);
        SocketChannel accept = serverSocketChannel.accept();
        while (true){
            int byteLen = 0;
            while (byteLen < 10){
               long redLne =  accept.read(byteBuffers);
                System.out.println("读取长度===="+redLne);
            }
            //写回客户端
            int writeByteLen = 0;
            while (writeByteLen<10){
                accept.write(byteBuffers);
            }
            Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.clear());
        }
    }
}
